const express = require('express');
const bodyParser = require('body-parser');
const path = require('node:path');

const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');

const app = express();
const PORT = 3000;


const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('database.db');

const JWT_SECRET = 'your-jwt-secret-key'; // 生产环境应从环境变量获取
// 初始化数据库表
db.serialize(() => {
    db.run(`CREATE TABLE IF NOT EXISTS texts (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        text TEXT NOT NULL,
        createdAt TEXT DEFAULT CURRENT_TIMESTAMP
    )`);
    
    db.run(`CREATE TABLE IF NOT EXISTS admin (
        id INTEGER PRIMARY KEY,
        password TEXT NOT NULL DEFAULT 'admin123'
    )`);
    
    // 设置默认管理员密码
    db.get("SELECT * FROM admin WHERE id = 1", (err, row) => {
        if (!row) {
            db.run("INSERT INTO admin (id, password) VALUES (1, 'admin123')");
        }
    });
});
app.use(express.json());  // 添加JSON解析中间件
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use(cookieParser());
// 首页 - 提交文本
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'submit.html'));
});
// 修改文本提交路由 - 创建资源
app.post('/api/texts', (req, res) => {
    const { text } = req.body;
    if (!text) return res.status(400).json({ error: '文本不能为空' });
    
    db.run("INSERT INTO texts (text) VALUES (?)", [text], function(err) {
        if (err) return res.status(500).json({ error: '提交失败' });
        res.status(201).json({ 
            id: this.lastID,
            message: '提交成功'
        });
    });
});
// 管理员登录页面
app.get('/admin', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'admin-login.html'));
});
// 管理员认证路由
app.post('/api/sessions', (req, res) => {
    const { password } = req.body;
    
    db.get("SELECT * FROM admin WHERE id = 1", (err, row) => {
        if (err || !row) return res.status(500).json({ error: '系统错误' });
        
        if (password === row.password) {
            const token = jwt.sign({ id: 1 }, JWT_SECRET, { expiresIn: '1h' });
            res.cookie('token', token, { 
                httpOnly: true,
                maxAge: 3600000
            });
            res.json({ message: '登录成功' });
        } else {
            res.status(401).json({ error: '密码错误' });
        }
    });
});




function verifyToken(req, res, next) {
    const token = req.cookies.token;
    if (!token) return res.redirect('/admin');
    
    try {
        req.user = jwt.verify(token, JWT_SECRET);
        next();
    } catch (err) {
        res.clearCookie('token');
        res.redirect('/admin');
    }
}

// 修改/admin/dashboard路由，使用新的验证中间件
app.get('/admin/dashboard', verifyToken, (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'admin-dashboard.html'));
});

// 修改为RESTful风格的管理面板路由
app.get('/api/texts', verifyToken, (req, res) => {
    db.all("SELECT * FROM texts ORDER BY createdAt ASC", (err, rows) => {
        if (err) return res.status(500).json({ error: '获取数据失败' });
        
        // 返回JSON格式数据
        res.json(rows.map(item => ({
            id: item.id,
            text: item.text,
            createdAt: item.createdAt
        })));
    });
});
app.delete('/api/texts/:id', verifyToken, (req, res) => {
    const { id } = req.params;
    db.run("DELETE FROM texts WHERE id = ?", [id], function(err) {
        if (err) return res.status(500).json({ error: '删除失败' });
        if (this.changes === 0) {
            return res.status(404).json({ error: '未找到该记录' });
        }
        res.sendStatus(204);
    });
});

// 添加退出登录路由
// 退出登录
app.delete('/api/sessions', (req, res) => {
    res.clearCookie('token');
    res.sendStatus(204);
});

app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});
